import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import store from '@/store'
/**
 * 单点登录
 */
const init = (callback) => {
  // let token = Vue.ls.get(ACCESS_TOKEN)
  let st = getUrlParam('ticket')
  let sevice = 'http://' + window.location.host + '/'
  // console.log(sevice)
  // if (token) {
  //   Vue.ls.remove(ACCESS_TOKEN)
  // }
  if (st) {
    validateSt(st, sevice, callback)
  } else {
    loginSuccess(callback)
  }
}
const SSO = {
  init: init,
}

function getUrlParam(paraName) {
  let url = document.location.toString()
  let arrObj = url.split('?')

  if (arrObj.length > 1) {
    let arrPara = arrObj[1].split('&')
    let arr

    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=')

      if (arr != null && arr[0] == paraName) {
        return arr[1]
      }
    }
    return ''
  } else {
    return ''
  }
}

function validateSt(ticket, sevice, callback) {
  let params = {
    token: ticket,
  }
  store
    .dispatch('ValidateLogin', params)
    .then((res) => {
      loginSuccess(callback)
    })
    .catch((err) => {
      loginSuccess(callback)
    })
}

function loginSuccess(callback) {
  callback()
}
export default SSO
